from django_redis import get_redis_connection
from rest_framework import serializers
from .models import OAuthQQUser
from users.models import User
class OauthQQSerializer(serializers.Serializer):

    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3456789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)

    def validate(self, attrs):
        #验证用户提交的access_token
        openid = OAuthQQUser.check_openid(attrs.get('access_token'))

        if openid is None:
            raise serializers.ValidationError('授权失败')

        attrs['openid'] = openid

        # 验证短信码
        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')

        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码错误')

        #需要根据手机号，查找用户是否存在，如果已经存在，直接绑定用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            #判断一下用户的密码是否输入正确
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码输入错误')

            attrs['user'] = user

        return attrs


    def create(self, validated_data):
        user = validated_data.get('user')

        if user is None:
            uesr = User.objects.create(
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password'),
                uesername = validated_data.get('mobile')
            )

        qquser = OAuthQQUser.objects.create(
                    openid=validated_data.get('openid'),
                    user=user)
        return user
